package com.big.pay.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.big.common.result.Result;
import com.big.common.utils.JsonUtils;
import com.big.common.utils.PayUtil;
import com.big.model.model.order.MerchandiseOrder;
import com.big.model.model.pay.PayLog;
import com.big.model.vo.pay.AlipayTradeQueryResponseVo;
import com.big.order.OrderFeignClient;
import com.big.pay.config.RabbitConfig;
import com.big.pay.service.PayLogService;
import com.big.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

/**
 *  支付宝业务实现
 * */
@Service
@Slf4j
public class PayServiceImpl implements PayService {


    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PayLogService payLogService;

    //应用id
    @Value("${alipay.appId}")
    private String appId;

    //私钥
    @Value("${alipay.privateKey}")
    private String privateKey;

    //公钥
    @Value("${alipay.publicKey}")
    private String publicKey;

    //支付宝网关
    @Value("${alipay.serverUrl}")
    private String serverUrl;

    //成功返回网址
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    //格式
    @Value("${alipay.format}")
    private String format;

    //字符集
    @Value("${alipay.charset}")
    private String charset;

    //支付宝标志类型
    @Value("${alipay.signType}")
    private String signType;

    /**
     *     App付款
     */
    @Override
    public Object pay(String oid) throws Exception {
        Result order = orderFeignClient.findOrder(oid);
        Object data = order.getData();
        //object 转class
        String StringInfo = JSONObject.toJSONString(data);
        System.out.println(StringInfo);
        MerchandiseOrder MerchandiseOrderInfo = JSONObject.parseObject(StringInfo, MerchandiseOrder.class);
        AlipayClient alipayClient =new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, publicKey, signType);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //交易订单流水号
        String out_trade_no = PayUtil.getOrderNo();
        request.setReturnUrl(returnUrl);//成功返回
        request.setNotifyUrl("http://d9pysy.natappfree.cC/api/pay/al/fallback/"+oid+"/"+out_trade_no); //回调
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", MerchandiseOrderInfo.getDTotal());
        bizContent.put("subject", MerchandiseOrderInfo.getDId());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        // 商品明细信息，按需传入

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
          log.info("支付成功");
        } else {
          log.error("支付失败");
        }
        return response.getBody();
    }


    /**
     * 成功回调
     * @param oid
     * @param outTradeNo
     * @return
     */
    @Override
    public Object fallback(@PathVariable("oid") String oid,@PathVariable("outTradeNo") String outTradeNo) {
        log.info("进去了回调");
        AlipayClient alipayClient =new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, publicKey, signType);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        request.setBizContent(bizContent.toString());
       AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            log.info("回调成功");
            //TODO 执行添加记录
            PayLog payLog = new PayLog();
            payLog.setDId(oid);
            payLog.setOutTradeNo(outTradeNo);
            payLog.setTradeNo(response.getTradeNo());
            /**
             * 发送支付记录队列-发送短信队列-发送短信队列-发送库存队列-发送订单队列-缓存删除
             */
            //记录交易记录
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_PAY,RabbitConfig.ROUTING_PAY_ITEM,payLog);
            //修改订单状态
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_ORDER_STATUS,RabbitConfig.ROUTING_ORDER_STATUS_ITEM,oid);
            //数量删减
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_STOCK,RabbitConfig.ROUTING_STOCK_ITEM,oid);
            //短信发送
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_MSM,RabbitConfig.ROUTING_MSM_ITEM,oid);

        } else {
            log.error("回调失败");
        }
        return response;
    }

    /**
     * 查询订单记录
     * @param oid
     * @return
     * @throws Exception
     */
    @Override
    public AlipayTradeQueryResponseVo payInfo(String oid) throws Exception {
        AlipayClient alipayClient =new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, publicKey, signType);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        PayLog payLog = payLogService.payLogInfo(Long.valueOf(oid));
        bizContent.put("out_trade_no", payLog.getOutTradeNo());
//      bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        AlipayTradeQueryResponseVo payFallbackVo =new AlipayTradeQueryResponseVo();
        //商家订单号
        payFallbackVo.setOutTradeNo(response.getOutTradeNo());
        //（支付）订单号
        payFallbackVo.setTradeNo(response.getTradeNo());
        //支付用户编号
        payFallbackVo.setBuyerUserId(response.getBuyerUserId());
        //订单状态码
        payFallbackVo.setTradeStatus(response.getTradeStatus());
        //支付金额
        payFallbackVo.setTotalAmount(response.getTotalAmount());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return payFallbackVo;
    }


}
